import re
import os
import subprocess
from datetime import datetime

def download_and_rename(url, target_folder):
    # 检查URL是否符合GitHub仓库的格式
    github_repo_pattern = re.compile(r'https://github.com/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)$')
    match = github_repo_pattern.match(url)
    
    if not match:
        raise ValueError("输入的URL不是有效的GitHub仓库地址。")
    
    # 构造下载链接
    user, repo = match.groups()
    download_url = f"https://github.com/{user}/{repo}/archive/master.zip"
    
    # 创建目标文件夹
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)
    
    # 下载文件
    try:
        subprocess.run(["wget", download_url], check=True)
    except subprocess.CalledProcessError as e:
        raise Exception(f"下载文件失败: {e}")
    
    # 重命名文件
    current_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
    new_filename = f"{user}_{repo}_{current_time}_github.com-master.zip"
    os.rename("master.zip", new_filename)
    new_file_path = os.path.join(target_folder, new_filename)
    os.rename(new_filename, new_file_path)
    
    # 返回重命名后文件的绝对路径
    return os.path.abspath(new_file_path)

def write_repo_info_to_file(url, file_path):
    # 检查文件是否已存在
    if os.path.exists(file_path):
        with open(file_path, 'r') as file:
            content = file.read()
            # 检查内容是否已包含当前URL
            if url in content:
                return False  # 如果已包含，则不写入

    # 获取用户和仓库名称
    github_repo_pattern = re.compile(r'https://github.com/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)$')
    match = github_repo_pattern.match(url)
    user, repo = match.groups()

    # 构造要写入的信息
    repo_info = f"URL: {url}\nUser: {user}\nRepository: {repo}\n\n"

    # 写入信息到文件
    with open(file_path, 'a') as file:
        file.write(repo_info)

    return True

# 示例使用
if __name__ == "__main__":
    try:
        url = input("请输入GitHub仓库URL: ")
        target_folder = "downloaded_repos"  # 存放.zip文件的文件夹
        txt_file_path = "repos_info.txt"  # 存储仓库信息的.txt文件
        abs_path = download_and_rename(url, target_folder)
        print(f"文件已下载并重命名为: {abs_path}")

        # 写入或更新仓库信息到.txt文件
        if write_repo_info_to_file(url, txt_file_path):
            print(f"仓库信息已写入到: {txt_file_path}")
        else:
            print(f"仓库信息已存在于: {txt_file_path}")
    except Exception as e:
        print(f"出现错误: {e}")
